<template>
    <div class="ele-body">
      <!-- 搜索表单 -->
      <saleorderSearch @search="reload"  />
      <!-- 数据表格 -->
      <el-card shadow="never">
        <ele-pro-table
          ref="table" :columns="columns" :datasource="datasource" :need-page="true" :cell-style="cellStyle"  @done="onDone"  :height="tableHeight" :full-height="tableFullHeight"
        >
          <!-- 表头工具栏 -->
          <template slot="toolbar">
            <el-button
              v-permission="'SaleOrder_Add'"
              size="small"
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              @click="openEdit({},1)"
            >
              添加
            </el-button>
            <el-button
              v-permission="'SaleOrder_Export'"
              size="small"
              icon="el-icon-upload2"
              class="ele-btn-icon"
              @click="reportexcel"
            >
              导出
            </el-button>
            <el-upload  ref="upload" size="small" :show-file-list="false" style="display: inline; margin-left: 10px;" action="#" :auto-upload="false" :on-change="handleChange" :limit="1">
              <el-button type="button" size="small" v-permission="'SaleOrder_Import'"
                  class="ele-btn-icon">
                  <i class="el-icon-download"></i><span>导入 </span>
              </el-button>
            </el-upload> &nbsp;
            <el-button
              size="small"
              icon="el-icon-download"
              class="ele-btn-icon"
              @click="download"
              v-permission="'SaleOrder_TemplateDownload'"
            >
              导入模板下载
            </el-button>
            <div class="ele-space" style="float: right; margin-top: 5px;">
              <el-button type="danger"  circle size="mini"></el-button>未出库
              <el-button type="primary"  circle size="mini"></el-button>出库中
              <el-button type="success"  circle size="mini"></el-button>已出库
              <div class="list-tool-divider" style="margin-right: 5px;margin-left: 5px;">
                <el-divider direction="vertical" />
              </div>
              <div class="list-tool-item" style="margin-right: 5px;">
                <span>作废数据</span>&nbsp;
                <el-switch
                  :active-value= 1
                  :inactive-value= 0
                  v-model="isDeleted"
                  @change="editState"
                  >
            </el-switch>
              </div>
              <div class="list-tool-divider" style="margin-right: 5px;">
                <el-divider direction="vertical" />
              </div>
          </div>
          </template>
           <!-- 标题列 -->
           <template slot="bNo" slot-scope="{ row }">
            <tr v-for="item in row.batchitems" :key='item.id' style="width: 100%;display: flex">
              <td style="width: 100%;align-items: center;margin-bottom: 3px;">
               <el-tag v-if="item.status == 5" type="success" size="medium" style="cursor: pointer;" @click="clickBatchNo(item)">{{ item.batchNo }}</el-tag>
               <el-tag v-else-if="item.status == 1"  type="danger" size="medium" style="cursor: pointer;" @click="clickBatchNo(item)">{{ item.batchNo }}</el-tag>
               <el-tag v-else  type="primary" size="medium" style="cursor: pointer;" @click="clickBatchNo(item)">{{ item.batchNo }}</el-tag>  
              </td>
            </tr>
          </template>
          <!-- 标题列 -->
          <template slot="status" slot-scope="{ row }">
            <el-tag type="danger" v-if="row.status==1">{{ row.statusDesc }}</el-tag>
            <el-tag type="success" v-else-if="row.status==5">{{ row.statusDesc }}</el-tag>
            <el-tag type="primary" v-else >{{ row.statusDesc }}</el-tag>
          </template>
           <!-- 操作列 -->
         <template slot="action" slot-scope="{ row }"  >
          <el-link type="primary" v-permission="'SaleOrder_List_Add'" :underline="false" v-show="row.status==1"  icon="el-icon-edit"  @click="openEdit(row,2)" >添加订单</el-link>
          <el-link type="primary" v-show="row.outStatus!=5" :underline="false" icon="el-icon-edit"  @click="openSaleOutOrder" >新增出库单</el-link>
          <el-link type="info"  :underline="false"  icon="el-icon-view"  @click="openEdit(row,3)" >详情</el-link>
          <el-popconfirm v-show="row.status==1 && row.deleted!=1" class="ele-action" title="确定要作废吗？"  @confirm="remove(row)" >
            <el-link type="danger" v-permission="'SaleOrder_Delete'" slot="reference" :underline="false"  icon="el-icon-delete" >作废</el-link>
          </el-popconfirm>
        </template>
        </ele-pro-table>
      </el-card>
      <!-- 导出数据 -->
      <ExportDialog ref="ExportDialog"></ExportDialog>
    </div>
  </template>
  
  <script>
    import { removePageTab } from '@/utils/page-tab-util';
    import upload from "@/components/UpLoad";
    import ExportDialog from '@/components/Excel/ExportDialog'
    import saleorderSearch from './components/saleorder-search.vue';
    import { QuerySaleorderByCondition ,ImportExcel,DeleteSaleorder} from '@/api/businesshandling/saleordermanager';

    export default {
      name: 'SaleOrder',
      mixins: [upload],
      components: {saleorderSearch,ExportDialog},
      data() {
        return {
          // 表格列配置
          columns: [
            {columnKey: 'index', type: 'index', width: 50, align: 'center', showOverflowTooltip: true, fixed: 'left', label:'序号',},
            {prop: 'orderNo', label: '订单号', showOverflowTooltip: true, align: 'center', fixed: 'left',sortable:'orderNo'},
            {prop: 'batchNo', label: '批次号',  width: 130, showOverflowTooltip: true,sortable:'batchNo', align: 'center',slot:'bNo', fixed: 'left', },
            {prop: 'customerName', label: '客户名称', width: 130,  showOverflowTooltip: true, align: 'center',},
            {
              prop: 'orderDate', label: '订单日期',width: 110,  showOverflowTooltip: true, align: 'center',
              formatter: (row, column, cellValue) => {return this.$util.toDateString(cellValue,"YYYY-MM-DD");}
            },
            {prop: 'currencyDesc', label: '币种',width: 90, showOverflowTooltip: true,align: 'center',},
            // {prop: 'orderAmount', label: '订单金额',  showOverflowTooltip: true, align: 'center',},
            // {prop: 'disAmount', label: '优惠金额',  showOverflowTooltip: true, align: 'center',},
            {prop: 'o_ActRecAmount', label: '应收金额', showOverflowTooltip: true, align: 'center',},
            {prop: 'preAmount', label: '预收款',  showOverflowTooltip: true, align: 'center',},
            {prop: 'o_recWaitAmount', label: '账户预收', showOverflowTooltip: true, align: 'center',},
            {prop: 'o_recAmount', label: '已收金额',  showOverflowTooltip: true,align: 'center',},
            {prop: 'o_returnAmount', label: '已退金额',  showOverflowTooltip: true,align: 'center',},
            {prop: 'o_recSurplusAmount', label: '未收金额',  showOverflowTooltip: true, align: 'center',},
            // 
            {prop: 'status', label: '状态', slot:'status',align: 'center', fixed: 'right', },
            {columnKey: 'action', label: '操作', width: 320, align: 'center', resizable: false,fixed: 'right', slot: 'action', hideInSetting: true, showOverflowTooltip: true}
          ],
          orderNo:'',
          orderId:'',
          //是否详情
          btnIndex: '1',
          isDeleted: 0,
          fixedHeight:true,
          // 当前编辑数据
          current: null,
          // 是否显示编辑弹窗
          showEdit: false,
          // 导出列
          exportList: [
            { name: "订单号", keys: "orderNo", status: true },
            { name: "批次号", keys: "batchNo", status: true },
            { name: "客户名称", keys: "customerName", status: true },
            { name: "订单日期", keys: "orderDate", status: true },
            { name: "币种", keys: "currencyDesc", status: true },
            { name: "订单金额", keys: "orderAmount", status: true },
            { name: "优惠金额", keys: "disAmount", status: true },
            { name: "应收金额", keys: "o_ActRecAmount", status: true },
            { name: "预收款", keys: "preAmount", status: true },
            { name: "账户预收", keys: "o_recWaitAmount", status: true },
            { name: "已收金额", keys: "o_recAmount", status: true },
            { name: '已退金额',keys: 'o_returnAmount', status: true},
            { name: "未收金额", keys: "o_recSurplusAmount", status: true },
            { name: "状态", keys: "statusDesc", status: true }
          ],
        };
      },
      computed: {
        // 表格高度
        tableHeight() {
          var fh = this.fixedHeight ? 'calc(100vh - 250px)' : void 0;
          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 126px)' : null;
          return fh;
        },
      },
      created(){
        this.orderNo = this.$route.query.orderNo;
        this.orderId = this.$route.query.orderId;
      },
      activated(){
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      },
      methods: {
        /* 表格数据源 */
        async datasource(params) {
          params.where.pageindex = params.page;
          params.where.pagesize = params.limit;
  
          //添加排序
          if(params.order.order == null || params.order.order == undefined){
            params.where.orderBys = [{ sort: "createDate", order: 1, }];
          }else{
            params.where.orderBys = [];
            params.where.orderBys.push({sort:params.sorter.column.sortable,order:params.order.order=='asc'?0:1});
          }

          if(!params.where.conditions)params.where.conditions= [];

          if(this.orderNo){
            params.where.conditions.push({
              key:"orderNo",
              operator: 0,
              value: this.orderNo,
            });
          }

          if(this.orderId){
            params.where.conditions.push({
              key:"id",
              operator: 0,
              value: this.orderId,
            });
          }

          let delIndex = params.where.conditions.findIndex((g)=>{
            return g.key == 'deleted';
          })

          if(delIndex>=0){
            params.where.conditions.splice(delIndex,1)
            params.where.conditions.push({ key:"deleted", operator: 0, value: this.isDeleted})
          }else{
            params.where.conditions.push({
              key:"deleted",
              operator: 0,
              value: this.isDeleted,
            });
          }

          let data = await QuerySaleorderByCondition(params.where);

          if(data && data.items){
            data.items.map((m)=>{
              m.grey = this.isDeleted;
            });
          }

        
          this.$nextTick(() => {
            this.$refs.table.doLayout();
          });

          return {
              list:data.items,
              count:data.totalrecords,
          };
        },
  
        /* 表格渲染完成回调 */
        onDone({ data }) {
          this.supplierList = data;
        },
        /* 刷新表格 */
        reload(where) {
          
          this.$refs.table.reload({ where: where });
          this.$nextTick(() => {
            this.$refs.table.doLayout();
          });
        },

        editState(){
          this.reload();
        },

        clickBatchNo(row){
          var path = '/businesshandling/saleordermanager/saleorderedit';
          removePageTab({ key:path });
          this.$nextTick(() => {
            this.$router.push({path: path, query: { "saleorderId": row.orderId,"isUpdate":3,"batchNo":row.batchNo} });
          });
        },
        
        /**
         * 显示编辑
         * @param row 当前行对像
         */
        openEdit(row,index) {
          var path = index == '3'?'/businesshandling/saleordermanager/saleorderitemedit':'/businesshandling/saleordermanager/saleorderedit'
          removePageTab({ key:path });
          this.$nextTick(() => {
            this.$router.push({path: path, query: { "saleorderId": row.id,"isUpdate":index} });
          });
        },

        openSaleOutOrder(){

          removePageTab({ key: '/businesshandling/saleoutmanger/saleoutedit' });
          this.$nextTick(() => {
            this.$router.push({path: '/businesshandling/saleoutmanger/saleoutedit', query: { "isUpdate":1} });
          });
        },

        /* 删除 */
        remove(row) {
          const loading = this.$loading({ lock: true });
          DeleteSaleorder(row.id)
            .then((msg) => {
              loading.close();
              this.$message.success(msg);
              this.reload();
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        },

        /*下载模板*/
        download(row){
          let a = document.createElement('a')
          a.href = "http://47.120.36.89:8091/file/importtemplates/salorder.xls";
          a.download = '销售订单模板.xlsx'
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
        },
        /* 导出 */
        reportexcel(pams) {

          //初始化参数
          let params = {
            pagesize: 0,
            pageindex: 1,
            conditions: [],
            orderBys: [{ sort: "createDate", order: 1, }],
          };
          //加载进度条
          const loading = this.$loading({ lock: true });
          //重新请求查询
          this.$refs.table.doRequest(({ where }) => {
          if(where){
            params.orderBys = where.orderBys;
            params.pageindex = where.pageindex;
            params.conditions = where.conditions;
          }
          //查询数据
          QuerySaleorderByCondition(params)
            .then((data) => {
              loading.close();
              this.$refs.ExportDialog.showEdits = true
              this.$refs.ExportDialog.checkList = this.exportList
              this.$refs.ExportDialog.titleName = "销售订单列表"
              this.$refs.ExportDialog.dataList = data.items;
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
          });
        },

        //导入
        handleChange(file) {
          let obj = {
            file: file.raw, // 文件流
            fileName: file.name, // 文件名称
            fileType: 2, // 文件类型(1:图片,2:文件)
          }
          this.uploadExeclPorts(obj);
        },

        async uploadExeclPorts(obj) {
          let param2 = new FormData();
          param2.append('file', obj.file);

          ImportExcel(param2).then((d)=>{

            
            if(d.code == 200){
              this.$message.success(d.msg);

              removePageTab({ key: this.$route.path });
              this.$router.push('/businesshandling/saleordermanager');

            }else{

              if(d.data== null || d.data ==''){
                this.$message.error(d.msg);
              }else{

                this.$confirm('数据导入异常,请下载异常信息', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.downloadExeclError(d.data);
                }).catch(() => {
                          
                });
              }
            }
            
            this.reload();
            this.$refs["upload"].clearFiles();

            this.$nextTick(() => {
              this.$refs.table.doLayout();
            });

          }).catch(e => {
            this.$message.error(e)
            this.reload();
            this.$refs["upload"].clearFiles();
          });
        },

        downloadExeclError(url) {
          let a = document.createElement('a')
          a.href = url
          a.download = '销售订单异常.xlsx'
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
        },

        /* 样式 */
        cellStyle(param){
          let cellStyle;
          const { row, column, rowIndex, columnIndex } = param;
          switch(row.grey == 1){
            case true:
              cellStyle = 'background-color: RGB(240,242,245)';
              break;
            default:
              cellStyle = '';
              break;
          }
          return cellStyle;
        },
      },
    };
  </script>